/******************************************************************************
 * @File name   :      Login.java
 *
 * @Author      :      chen shixiang
 *
 * @Date        :      2011-10-9
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-10-9 上午09:28:58        chen shixiang     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.framework.workbench.userlogin.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo;
import com.cap.bts.crmdp.dealer.masterdata.dto.DealerOperationPwdDto;
import com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService;
import com.cap.bts.framework.workbench.userlogin.dto.OperationPwdDto;
import com.cap.bts.framework.workbench.userlogin.dto.UpdatePwdDto;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.menu.constant.MenuTypeConstants;
import com.cap.bts.framework.menu.dto.MenuItemDto;
import com.cap.bts.framework.menu.service.IMenuService;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;
import com.cap.bts.framework.usermgnt.util.PasswordUtil;

/**
 *
 */
@Controller
@RequestMapping(value = "/login")
public class LoginUpdatePwdController extends BaseController {
    
    @Autowired
    private IUserMgntService userService;
    @Autowired
    private IMaintainDealerService maintainDealerService;
    @Autowired
    private IMenuService menuService;
    
    @RequestMapping(value="/toUpdate",method=RequestMethod.GET)
    public String toUpdate(Model model){
        User user = getCurrentUser();
        UpdatePwdDto updatePwdDto = new UpdatePwdDto();
        updatePwdDto.setUserId(user.getId());
        model.addAttribute("userDto", updatePwdDto);
        return "/workbench/updatepwd";
    }
    //用于测试的界面，之后有实际界面后可删除
    @RequestMapping(value="/toUpdateTest",method=RequestMethod.GET)
    public String toUpdateTest(Model model){
        User user = getCurrentUser();
        UpdatePwdDto updatePwdDto = new UpdatePwdDto();
        updatePwdDto.setUserId(user.getId());
        model.addAttribute("userDto", updatePwdDto);
        return "/workbench/updatepwd";
    }
    
    @RequestMapping(value="/toFirstLoginUpdatePwd",method = RequestMethod.GET)
    public String toFirstLoginUpdatePwd(Model model){
        User user = getCurrentUser();
        UpdatePwdDto updatePwdDto = new UpdatePwdDto();
        updatePwdDto.setUserId(user.getId());
        model.addAttribute("userDto", updatePwdDto);
        return "/workbench/firstLoginUpdatepwd";
    }
    
    @RequestMapping(value="/toupdateoperationpwd",method = RequestMethod.GET)
    public String toupdateoperationpwd(Model model,HttpServletRequest req) throws AppException{
        User user = getCurrentUser();
        DealerOperationPwdDto dealerOperationPwdDto = new DealerOperationPwdDto();
        dealerOperationPwdDto.setDealerNum(user.getUserCode());
        //获取首页url
        String homePage = "#";
        User currUser = (User) req.getSession().getAttribute("userSession");
        List<MenuItemDto> userMenus = menuService.getDisplayMenus(currUser.getUserCode(),MenuTypeConstants.DEALER);
        if(userMenus != null && !userMenus.isEmpty()){
            List<MenuItemDto> list = userMenus.get(0).getSubMenus();
            if(list != null && !list.isEmpty()){
                homePage = list.get(0).getMenuUrl();
            }
        }
        model.addAttribute("homePage", homePage);
        model.addAttribute("dealerOperationPwdDto", dealerOperationPwdDto);
        return "/workbench/updateoperationpwd";
    }
    
    @RequestMapping(value="/checkOldOperationPwdById/{passwd}")
    @ResponseBody
    public Boolean checkOldOperationPwdById(@RequestParam("oldPassword") String oldpwd,@PathVariable("passwd")String passwd) throws AppException{
        User user = getCurrentUser();
        String dealerNum = user.getUserCode();
        MasterDataDealerInfo dealerInfo = maintainDealerService.getDealerByDealerNum(dealerNum);
        String decryptedPwd = PasswordUtil.decodePassword(dealerInfo.getOperationPassword());
        if(Utils.notEmpty(oldpwd) && Utils.notEmpty(passwd) && !oldpwd.equals(passwd)){
            passwd = oldpwd;
        }
        if(decryptedPwd.equals(passwd)){
            return true;
        }
        return false;
    }
    
    @RequestMapping(value="/checkOldPwdById/{passwd}")
    @ResponseBody
    public Boolean checkOldPwdById(@RequestParam("oldPassword") String oldpwd,@PathVariable("passwd")String passwd) throws AppException{
        User user = getCurrentUser();
        User userInfo = userService.getUserByUserCode(user.getUserCode());
        String decryptedPwd = PasswordUtil.decodePassword(userInfo.getPassword());
        if(Utils.notEmpty(oldpwd) && Utils.notEmpty(passwd) && !oldpwd.equals(passwd)){
        	passwd = oldpwd;
        }
        if(decryptedPwd.equals(passwd)){
            return true;
        }
        return false;
    }
    
    @RequestMapping(value="/updateOperationPwd",method = RequestMethod.POST)
    public String updateOperationPwd(Model model,DealerOperationPwdDto dealerOperationPwdDto) throws AppException{
        MasterDataDealerInfo dealerInfo = maintainDealerService.getDealerByDealerNum(Long.toString(UserUtil.getCurrentUser().getDealerId()));
        dealerInfo.setOperationPassword(PasswordUtil.encodePassword(dealerOperationPwdDto.getOperationPassword()));
        dealerInfo.setLastOpreationPwdChangeTime(new Date());
        maintainDealerService.updateDealer(dealerInfo);
        model.addAttribute("dealerOperationPwdDto", new DealerOperationPwdDto());
        model.addAttribute("message", "xiugaichenggon");
        return "/workbench/updateoperationpwd";
    }
    
    @RequestMapping(value="/tofirstUpdateOperationPwd",method = RequestMethod.GET)
    public String tofirstUpdateOperationPwd(Model model){
        User user = getCurrentUser();
        DealerOperationPwdDto dealerOperationPwdDto = new DealerOperationPwdDto();
        dealerOperationPwdDto.setDealerNum(user.getUserCode());
        model.addAttribute("dealerOperationPwdDto", dealerOperationPwdDto);
        return "/workbench/loadlayerupdateoperationpwd";
    }
    
    @RequestMapping(value="/firstUpdateOperationPwd",method = RequestMethod.POST)
    @ResponseBody
    public boolean firstUpdateOperationPwd(DealerOperationPwdDto dealerOperationPwdDto) throws AppException{
        try {
            MasterDataDealerInfo dealerInfo = maintainDealerService.getDealerByDealerNum(dealerOperationPwdDto.getDealerNum());
            dealerInfo.setOperationPassword(PasswordUtil.encodePassword(dealerOperationPwdDto.getOperationPassword()));
            dealerInfo.setLastOpreationPwdChangeTime(new Date());
            return maintainDealerService.updateDealer(dealerInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @RequestMapping(value="/firstLoginUpdatePwd",method = RequestMethod.POST)
    @ResponseBody
    public boolean firstLoginUpdatePwd(UpdatePwdDto userDto) throws AppException{
        try {
            User user = userService.getUserByUserId(userDto.getUserId());
            user.setPassword(PasswordUtil.encodePassword(userDto.getPasswd()));
            user.setLastPwdChangeTime(new Date());
            return userService.updateUser(user);
           
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @RequestMapping(value="/updatePwd",method = RequestMethod.POST)
    public String updatePwd(Model model,UpdatePwdDto userDto) throws AppException{
        User user = userService.getUserByUserId(getCurrentUser().getId());
        user.setPassword(PasswordUtil.encodePassword(userDto.getPasswd()));
        user.setLastPwdChangeTime(new Date());
        userService.updateUser(user);
        model.addAttribute("userDto", new UpdatePwdDto());
        model.addAttribute("message", "xiugaichenggon");
        return "/workbench/updatepwd";
    }
    
}
